const _ = require('lodash');
const pinyin = require('pinyin');

export const createAlphabetList = (list, property) => {
  let first, alphabet, alphabets, AlphabetList = {};
  // const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  // _.map(letters, (element) => AlphabetList[element] = [])
  _.map(list, (element) => {
    _.map(element, (value, key) => {
      if (element.hasOwnProperty(property) && key === property) {
        alphabet = translate(value)
        if (AlphabetList.hasOwnProperty(alphabet) && AlphabetList[alphabet].indexOf(element) < 0) {
          AlphabetList[alphabet].push(element)
        } else {
          AlphabetList[alphabet] = [element]
        }
      }
    })
  })
  return sortObjectByKey(AlphabetList);
}

export const translate = (value) => {
  let alphabets, alphabet;
  alphabet = (alphabets = pinyin(value)).length ?
   _.first(_.first(alphabets)).charAt(0).toUpperCase() : value.charAt(0).toUpperCase()
  alphabet = /^[A-Z]$/.test(alphabet) ? alphabet : 'Z'
  return alphabet
}

export const sortObjectByKey = (object) => {
  let fresh = {}
  _(object).keys().sort().map(function (key) {
    if (object[key] && object[key].length > 0) {
      fresh = _.extend({}, fresh, {[key]: object[key]})
    }
  }).value();
  return fresh;
}
